package com.sjsu.aws.readwritelocks;

/**
 * 
 * @author Shweta Dattatreya
 * 
 */

public class ReadWriteLockTestNode extends Thread {

	String name;
	ReadWriteLock lock;
	boolean lockRequested;
	boolean lockAcquired;

	private class LockListenerImpl implements LockListener {
		public void lockAcquired() {
			lockAcquired = true;
			System.out.println(name + " : Acquired Lock");
			System.out.println(name + "is the Leader");
		}

		public void lockReleased() {
			System.out.println(name + " : Released Lock");
		}

		public void lockRenewed() {
			System.out.println(name + " : Renewed Lock");

		}
	}

	public ReadWriteLockTestNode(String n) {
		name = n;
		lockAcquired = false;
		try {
			lock = new ReadWriteLock();
			lock.setLockListener(new LockListenerImpl());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	int getWaitTime() {
		double rand = Math.random();
		int wait = (int) (rand * 100);
		return (wait * 5);
	}

	public void run() {
		try {
			// request lock
			if (!lockRequested) {
				Thread.sleep(getWaitTime() * 10);
				lock.lock();
			}
			// wait till lock is acquired
			while (!lockAcquired) {
				Thread.sleep(getWaitTime() * 10);
			}
			// release lock
			Thread.sleep(getWaitTime() * 10);

			// renew lock uncomment next two lines
			// lock.renew();
			// Thread.sleep(getWaitTime() * 10);

			// To check ephemeral node comment next two lines
			lock.unlock();
			System.out.println(name + " : Exiting...");
		} catch (Exception e) {
			// System.out.println(name + ": " + e.getMessage());
			e.printStackTrace();
		}
	}
}
